import List "mo:base/List";
import Iter "mo:base/Iter";
import Principal "mo:base/Principal";
import Time "mo:base/Time";

actor {

public type Message = {
   time : Time.Time;
   mess : Text;
};

public type Microblog = actor {
    follow: shared(Principal)-> async (); //添加关注对象
    follows: shared query () -> async [Principal]; //返回关注列表
    post: shared (Text) -> async ();
    posts: shared query (Time.Time) -> async [Message];
    timeline: shared () -> async [Message];
    };

  stable var followed: List.List<Principal> = List.nil();

  public shared func follow(id : Principal) : async () {
    followed := List.push(id,followed);
  };
  public shared query func follows() : async [Principal]{
    List.toArray(followed)
  };

  stable var messages: List.List<Message> = List.nil();

  public shared (user) func post(text:Text):async () {
    assert(Principal.toText(user.caller)=="6axso-2bbmh-43arq-uqvwy-scpuo-qijcs-zlamd-7ldxf-73er2-f4rby-uae");
    let new_message:Message = {
       time = Time.now();
       mess = text;
    };
    messages := List.push(new_message,messages);
  };
  // public shared query func posts():async [Message]{
  //   List.toArray(messages)
  // };
  public shared query func posts(since:Time.Time):async [Message]{
    
    var after_messages: List.List<Message> = List.nil();

    for (mg in Iter.fromList(messages)){
    if (mg.time - since > 0) after_messages := List.push(mg,after_messages);
    };
    List.toArray(after_messages)
  };


  public shared func timeline(since:Time.Time):async [Message]{
    var all :List.List<Message> = List.nil();
    
    for (id in Iter.fromList(followed)){
        let canister : Microblog = actor(Principal.toText(id));
        let msgs = await canister.posts(since:Time.Time);
        for (msg in Iter.fromArray(msgs)){
          all := List.push(msg,all)
        }
    };
    List.toArray(all)
  };

};
